# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth.models import User
from registration.forms import attrs_dict
from main.models import UserInfo, ImageLoadClass, City, Company, WallMessage, Discussion, DiscussionMessage, GlobalType, Good, Offer, Order, ResponseToOrder, NotifySettings
from django.utils.translation import ugettext_lazy as _
import settings


class UploadImageForm(forms.ModelForm):
     class Meta:
         model = ImageLoadClass

class UserInfoForm(forms.ModelForm):
    class Meta:
        model  = UserInfo
        fields = ['first_name','last_name','sex','birthday','phone','icq','skype','vkontakte','website','email','contacts','status','my_auto','area']






class ExtendedRegistrationFormUniqueEmail(forms.Form):
    first_name = forms.CharField(required=True, widget=forms.TextInput(attrs=dict(maxlength=75)), label=_("Name"))
    last_name = forms.CharField(required=True, widget=forms.TextInput(attrs=dict( maxlength=75)), label=u"Фамилия")
    email = forms.EmailField(required=True, widget=forms.TextInput(attrs=dict( maxlength=75)), label=_("Email address"))
    password1 = forms.CharField(required=True, widget=forms.PasswordInput(render_value=False), label=_("Password"))
    password2 = forms.CharField(required=True, widget=forms.PasswordInput(render_value=False), label=_("Password (again)"))
    username = forms.RegexField(required=True,
                                regex=r'^\w+$',
                                max_length=30,
                                widget=forms.TextInput(attrs=attrs_dict),
                                label=_("Username"),
                                error_messages={ 'invalid': _("This value must contain only letters, numbers and underscores.") })
    




    def clean(self):
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_("The two password fields didn't match."))
        return self.cleaned_data

    def clean_email(self):
        if User.objects.filter(email__iexact=self.cleaned_data['email']):
            raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
        return self.cleaned_data['email']

    def clean_first_name(self):
        if self.cleaned_data.get('first_name', False):
            return self.cleaned_data['first_name']
        raise forms.ValidationError("Обязательное поле!")

    def clean_last_name(self):
        if self.cleaned_data.get('last_name', False):
            return self.cleaned_data['last_name']
        raise forms.ValidationError("Обязательное поле!")

    def clean_username(self):
        if self.cleaned_data.get('first_name', False):
            if self.cleaned_data.get('last_name', False):
                return unicode(self.cleaned_data['first_name']+'_'+self.cleaned_data['last_name']).encode('trans')
        raise forms.ValidationError("Заполните имя и фамилию!!")


class PasswordChangeForm(forms.Form):
    old_password = forms.CharField(required=True, widget=forms.PasswordInput(render_value=False), label=_("Old password"))
    new_password1 = forms.CharField(required=True,widget=forms.PasswordInput(render_value=False), label=_("New password"))
    new_password2 = forms.CharField(required=True,widget=forms.PasswordInput(render_value=False), label=_("New Password (again)"))

    def clean(self):
        if 'new_password1' in self.cleaned_data and 'new_password2' in self.cleaned_data:
            if self.cleaned_data['new_password1'] != self.cleaned_data['new_password2']:
                raise forms.ValidationError(_("The two password fields didn't match."))
        return self.cleaned_data


class EmailChangeForm(forms.Form):
    email = forms.EmailField(required=True, label=_("e-mail"))
    def clean_email(self):
        try:
            user = User.objects.get(email = self.cleaned_data['email'])
        except:
            return self.cleaned_data['email']
        if user:
            raise forms.ValidationError("Такой e-mail уже используется!")


class AddCompanyForm(forms.ModelForm):
    class Meta:
        model  = Company
        fields = ['name','categories','ownership_type','phone','ur_address','fiz_address']

class EditCompanyForm(forms.ModelForm):
    class Meta:
        model  = Company
        fields = ['name','logo','worktime','fiz_address','phone','skype','icq','email','website','description','activities', 'categories','owner']#,'country','city',

class PartnerForm(forms.Form):
    partner_url = forms.CharField(label=u"Ссылка на партнёра", max_length = 150)
    def clean_partner_url(self):
        url = str(self.cleaned_data['partner_url'])
        if url.find('/company/')>0:
            parts = url.split('/')
            if url.startswith("http://"):
                return parts[4]
            else:
                return parts[2]
        else:
            raise forms.ValidationError(u"Неправильная ссылка!")

class WallCommentForm(forms.ModelForm):
    class Meta:
        model = WallMessage
        fields = ["text", "sender", "recipient"]

class DiscussionForm(forms.ModelForm):
    class Meta:
        model = Discussion
        fields = ["subj"]
    #def __init__(self, *args, **kwargs):
    #    super(DiscussionForm, self).__init__(*args, **kwargs)
    #    self.fields["type"].initial = GlobalType.objects.get(name__iexact = settings.GLOBAL_TYPE)


class DiscussionMessageForm(forms.ModelForm):
    class Meta:
        model = DiscussionMessage
        fields = ["text"]

class GoodForm(forms.ModelForm):
    class Meta:
        model = Good
        fields = ["name", "image", "description", "price"]

class OfferForm(forms.ModelForm):
    class Meta:
        model = Offer
        fields = ["text"]

class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ["subj","text","price","active"]


class ResponseForm(forms.ModelForm):
    class Meta:
        model = ResponseToOrder
        fields = ["company","text"]

class NotifySettingsForm(forms.ModelForm):
    class Meta:
        model = NotifySettings
        fields=["notify_friends", "notify_order_response", "notify_new_companies", "notify_wall_comments"]



class SupportForm(forms.Form):
    email = forms.EmailField(label='Ваш e-mail', required=True)
    text = forms.CharField(label='Текст сообщения',  widget=forms.widgets.Textarea(), required=True )

CHOICES=(('1', u'По пользователям'),
         ('2', u'По компаниям'),
         ('3', u'По обсуждениям'),
         ('4', u'По предложениям'),
         ('5', u'По заказам')
        )

class SearchForm(forms.Form):
    search_q = forms.CharField(required=True)
    where_to_look=forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)